package org.linphone.yinpin;

import com.leehuubsd.yiyanzb.R;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class ScrollPositionDotView extends LinearLayout {

	private int mTotal;

	private int mCurrentSelectedNum;

	public ScrollPositionDotView(Context context, AttributeSet attrs) {
		super(context, attrs);
		setOrientation(LinearLayout.HORIZONTAL);
	}

	private static final int DOT_SPACE = 10;

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		if (getChildCount() > 0) {
			setMeasuredDimension(getChildCount() * (getChildAt(0).getMeasuredWidth() + DOT_SPACE),getChildAt(0).getMeasuredHeight());
		} 
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {

		if (getChildCount() > 0) {
			for (int num = 0; num < getChildCount(); num++) {
				View view = getChildAt(num);
				int measureHeight = view.getMeasuredHeight();
				int measuredWidth = view.getMeasuredWidth();
				view.layout(num * (measuredWidth + DOT_SPACE), 0, num
						* (measuredWidth + DOT_SPACE) + measuredWidth,
						measureHeight);
			}
		}
	}

	public void setDotCount(int count) {
		if (count > 0) {
			removeAllViews();
			for (int num = 0; num < count; num++) {
				ImageView imageView = new ImageView(getContext());
				imageView.setBackgroundDrawable(null);
				imageView.setImageResource(R.drawable.dot_view);
				addView(imageView);
			}
			getChildAt(0).setSelected(true);
			requestLayout();
			mTotal = count;
		}
	}

	public void setSelectNum(int selectNum) {
		if (selectNum >= 0 && selectNum < getChildCount()) {
			for (int num = 0; num < getChildCount(); num++) {
				if (num == selectNum) {
					getChildAt(num).setSelected(true);
				} else {
					getChildAt(num).setSelected(false);
				}
			}
			mCurrentSelectedNum = selectNum;
		}
	}

	public void selectNext() {
		if (mTotal > 0) {
			if (mCurrentSelectedNum < mTotal - 1) {
				setSelectNum(mCurrentSelectedNum + 1);
			} else {
				setSelectNum(0);
			}
		}
	}

	public void selectPre() {
		if (mTotal > 0) {
			if (mCurrentSelectedNum > 0) {
				setSelectNum(mCurrentSelectedNum - 1);
			} else {
				setSelectNum(mTotal - 1);
			}
		}
	}
}